package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultDTO;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.edais.dao.CenterDao;
import com.edais.dao.WalletDao;
import com.edais.domain.AgreementMirror;
import com.edais.service.WalletService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.Message;
import com.edais.util.StringUtil;
import com.edais.vo.FundFlowDetailVo;
import com.edais.vo.FundFlowVo;
import com.edais.vo.PurchaseDetailVo;
import com.edais.vo.RepaymentDetailVo;
import com.edais.vo.WalletCreditVo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import static javafx.scene.input.KeyCode.H;

@Service

public class WalletServiceImp implements WalletService {
	private static final Log logger = LogFactory.getLog(WalletServiceImp.class);
	
	@Autowired
	private WalletDao walletDao;
	@Autowired
	private CenterDao  centerDao;
	
	/**
	 * E400014 我的钱包统计信息(调用核心接口) E320001我的钱包统计信息
	 * 
	 * */
	@Override
	public String getStatisticsInfor(String jsonStr) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		
		/**
		 * 调用核心接口 E320001
		 * */
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			rtnMap.put("incomeAlready", jsonObject.getString("incomeAlready"));            // 已收回款（9990.00元）
			rtnMap.put("incomeWait", jsonObject.getString("incomeWait"));                  // 未收回款（9990.00元）
			rtnMap.put("incomeAlreadyRatio", jsonObject.getString("incomeAlreadyRatio"));  // 已收回款比率（%）
			rtnMap.put("investAmountTotal", jsonObject.getString("investAmountTotal"));    // 历史投资总额（9990.00元）
			rtnMap.put("expectAmountTotal", jsonObject.getString("expectAmountTotal"));    // 预期总回款（9990.00元）
			rtnMap.put("matchingAmount", jsonObject.getString("matchingAmount"));          // 匹配中金额（9990.00元）
			
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			
		} else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}
	
	/**
	 * E400015 我的钱包下期回款信息(调用核心接口) E320002
	 * 
	 * */
	@Override
	public String getNextIncomeInfor(String jsonStr) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		
		/**
		 * 调用核心接口 E320002
		 * */
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			rtnMap.put("nextReceiptDate", jsonObject.getString("nextReceiptDate"));  // 下一收款日期(yyyy/MM/dd)
			rtnMap.put("incomeNext", jsonObject.getString("incomeNext"));            // 下期回款（格式：9990.00元）
			
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
		} else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}
	
	/**
	 * 调用核心【E330003已购买订单列表(产品扩展，时间金额排序)】接口
	 * 
	 **/

	@Override
	public String getPurchaseDetail(String jsonStr) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<PurchaseDetailVo> purchaseDetailList = new ArrayList<PurchaseDetailVo>();
		
		/**
		 * 调用核心【E330020已购买订单列表(产品扩展，时间金额排序)】接口
		 * */
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			int totalNum = jsonObject.getInt("totalNum");
			if(totalNum>0){
				JSONArray jsonArr = jsonObject.getJSONArray("list");
				if(jsonArr != null && jsonArr.size() > 0){
					for(int i = 0; i < jsonArr.size(); i++){
						JSONObject jsonObj = jsonArr.getJSONObject(i);
						PurchaseDetailVo purchaseDetail = new PurchaseDetailVo();
						purchaseDetail.setOrderId(jsonObj.getString("orderId"));
						//订单状态
	//					if("1".equals(jsonObj.getString("orderState"))){
	//						// 匹配中--签约中
	//						purchaseDetail.setOrderState("签约中");
	//					}else if("2".equals(jsonObj.getString("orderState"))){
	//						// 回款中
	//						purchaseDetail.setOrderState("回款中");
	//					}else if("3".equals(jsonObj.getString("orderState"))){
	//						// 回款完成
	//						purchaseDetail.setOrderState("回款完成");
	//					}else if("4".equals(jsonObj.getString("orderState"))){
	//						// 回款完成
	//						purchaseDetail.setOrderState("已退出");
	//					}
						//2.0不再进行翻译
						purchaseDetail.setOrderState(jsonObj.getString("orderState"));
						
						purchaseDetail.setPreMatchAmount(jsonObj.getString("preMatchAmount"));
						purchaseDetail.setInvestAmount(jsonObj.getString("investAmount"));
						purchaseDetail.setInvestDate(jsonObj.getString("investDate"));
						//资产价值。即，订单的债权价值=订单的现金价值
						purchaseDetail.setOrderValue(jsonObj.getString("orderValue"));
						//锁定时间（天）
						if (Integer.valueOf(jsonObj.getString("lockTime")) <= 0) {
							purchaseDetail.setLockTime("0");
						} else {
							purchaseDetail.setLockTime(jsonObj.getString("lockTime") + "");
						}
						//债权有无标志
						purchaseDetail.setCreditFlag(jsonObj.getString("creditFlag"));
						
						// qiu add 2014/09/10，理财产品id、理财产品名称
						purchaseDetail.setFinanceID(jsonObj.getString("financeID"));
						purchaseDetail.setFinanceName(jsonObj.getString("financeName"));
						
						// zhangzh add 2015/01/9，主理财产品名称，基础锁定期
						purchaseDetail.setFinanceNameMain(jsonObj.getString("financeNameMain"));
						purchaseDetail.setBaseLockPeriod(jsonObj.getString("baseLockPeriod"));
						purchaseDetail.setMainFinanceId(jsonObj.getString("mainFinanceId"));
						purchaseDetail.setLastUpateDate(jsonObj.getString("lastUpateDate"));
						purchaseDetail.setIncome(jsonObj.getString("income"));
						purchaseDetail.setAssignFlag(jsonObj.getString("assignFlag"));
						purchaseDetailList.add(purchaseDetail);
					}
				}
				rtnMap.put("totalNum", jsonObject.getString("totalNum"));
				rtnMap.put("listSize", purchaseDetailList.size());
				rtnMap.put("list", purchaseDetailList); 
			}else{
				rtnMap.put("totalNum", 0);
				rtnMap.put("listSize", 0);
				rtnMap.put("list", new ArrayList()); 
			}
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
		} else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}
	
	/**
	 * E400017 债权列表
	 * 
	 * */

	@Override
	public String getCreditDetail(String jsonStr) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<WalletCreditVo> walletCreditList = new ArrayList<WalletCreditVo>();
		
		/**
		 * 调用核心接口 E300020
		 * */
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){
				for(int i = 0; i < jsonArr.size(); i++){
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					WalletCreditVo walletCredit = new WalletCreditVo();
					walletCredit.setCreditId(jsonObj.getString("creditId"));
					//服务端返回数字，客户端进行翻译
//					if ("2".equals(jsonObj.getString("creditState"))) {
//						walletCredit.setCreditState("回款中");
//					} else if ("3".equals(jsonObj.getString("creditState"))) {
//						walletCredit.setCreditState("回款完成");
//					} else if ("6".equals(jsonObj.getString("creditState"))) {
//						walletCredit.setCreditState("已转让");
//					}
					walletCredit.setCreditState(jsonObj.getString("creditState"));
					
					walletCredit.setCreditAmount(jsonObj.getString("creditAmount"));
					walletCredit.setRate(jsonObj.getString("rate"));
					walletCredit.setLoanPeriods(jsonObj.getString("loanPeriods"));
					walletCredit.setResidualPeriods(jsonObj.getString("residualPeriods"));
					walletCredit.setCashValue(jsonObj.getString("cashValue"));
					walletCredit.setCreditDate(jsonObj.getString("creditDate"));
					walletCredit.setProductName(jsonObj.getString("productName"));
					walletCredit.setBorrowType(jsonObj.getString("borrowType"));
					
					walletCreditList.add(walletCredit);					
				}
			}
			
			rtnMap.put("totalNum", jsonObject.getString("totalNum"));
			rtnMap.put("listSize", walletCreditList.size());
			rtnMap.put("list", walletCreditList); 
			
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
		} else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}
	

	/**
	 * E400018 还款详情列表(调用核心接口) 
	 * 1.0时，调用核心接口 E300020我的收款分期明细;
	 * 1.5时，调用新核心接口 E330010 收款详情列表
	 * */
	@Override
	public String getRepaymentDetail(String jsonStr) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<RepaymentDetailVo> repaymentDetailList = new ArrayList<RepaymentDetailVo>();
		
		/**
		 * 调用核心接口
		 * */
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){
				for(int i = 0; i < jsonArr.size(); i++){
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					RepaymentDetailVo repaymentDetail = new RepaymentDetailVo();
					
					repaymentDetail.setCurrPeriods(jsonObj.getString("PERIODS"));
					repaymentDetail.setNeedReceiptDay(this.changeDateFormat(jsonObj.getString("NEEDRESEIPTDAY")));
					//服务端返回数字，客户端进行翻译
					// 每一期回款状态（核心：0.本期应收1.正常已收2.未到期3.逾期已收4.逾期未收5.提前收款）手机展示：0,2,4--未回款；1,3,5--已回款
//					if("0".equals(jsonObj.getString("RESEIPTSTATE")) || 
//					   "2".equals(jsonObj.getString("RESEIPTSTATE")) ||
//					   "4".equals(jsonObj.getString("RESEIPTSTATE"))){
//						repaymentDetail.setReceiptState("未回款");
//					} else if("1".equals(jsonObj.getString("RESEIPTSTATE")) || 
//							  "3".equals(jsonObj.getString("RESEIPTSTATE")) || 
//							  "5".equals(jsonObj.getString("RESEIPTSTATE"))){
//						repaymentDetail.setReceiptState("已回款");
//					}else if("6".equals(jsonObj.getString("RESEIPTSTATE"))){
//						repaymentDetail.setReceiptState("已转让");
//					}
					repaymentDetail.setReceiptState(jsonObj.getString("RESEIPTSTATE"));
					
					repaymentDetail.setNeedReceiptPrincipal(new BigDecimal(jsonObj.getString("NEEDRESEIPTPRINCIPAL")).setScale(2, BigDecimal.ROUND_DOWN).toString());
					repaymentDetail.setNeedReceiptInterest(new BigDecimal(jsonObj.getString("NEEDRESEIPTINTEREST")).setScale(2, BigDecimal.ROUND_DOWN).toString());
					repaymentDetail.setHadReceiptPrincipal(new BigDecimal(jsonObj.getString("HADRESEIPTPRINCIPAL")).setScale(2, BigDecimal.ROUND_DOWN).toString());
					repaymentDetail.setHadReceiptInterest(new BigDecimal(jsonObj.getString("HADRESEIPTINTEREST")).setScale(2, BigDecimal.ROUND_DOWN).toString());
					
					repaymentDetailList.add(repaymentDetail);
				}
			}
			
			if(jsonObject.get("loanPeriods") == null || "".equals(jsonObject.get("loanPeriods"))){
				rtnMap.put("totalNum", "0");
			} else {
				rtnMap.put("totalNum", jsonObject.get("totalNum"));
			}

			rtnMap.put("listSize", repaymentDetailList.size());
			rtnMap.put("list", repaymentDetailList); 
			
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			
		} else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}
	
	/**
	 *  资金流水
	 * */
	@Override
	public ResultDTO getFundFlowDetail(String jsonStr, Integer current, Integer pageSize) throws Exception {
		/**
		 * 调用核心接口 E330004
		 * */
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(rtnStr);
		ResultDTO result;
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			com.alibaba.fastjson.JSONArray jsonArr = jsonObject.getJSONArray("list");
			int totalNum = jsonObject.getIntValue("totalNum");
			result = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),
					ResultCode.SUCCESS.getType(),pageSize,totalNum,jsonArr);
		} else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			result=new ResultDTO(ResultCode.FAILED);
		}
		return result;
	}
	
	/***
	 * 获取资金流水的类型
	 * @param productType 
	 * @return
	 */
	private String getfundFlowValue(String fundType, String productType){
		HashMap<String, String> hashMap = new HashMap<String, String>();
		// 鼓钱包理财人展现资金类型(1、活动返还;2、网站充值;3、提现;4、提现手续费;5、加入e计划;6、加入e贷通;7、本金回款;8、收益回款;
		// 9、转让收入;10、转让手续费;25、冲账;30、提现申请;31、加入涨薪宝;34、鼓钱包充值;35、邀请返现;37、签约中资金退出;)
		hashMap.put("1", "活动返还");
		hashMap.put("2", "充值");
		hashMap.put("3", "提现");
		hashMap.put("4", "提现手续费");
		//hashMap.put("5", "加入e计划");
		
		//hashMap.put("6", "加入e贷通");
		
		hashMap.put("5", "定期购买");
		hashMap.put("6", "定期购买");
		
		hashMap.put("7", "本金回款");
		hashMap.put("8", "收益回款");
		hashMap.put("9", "转让收入");
		hashMap.put("10", "转让手续费");
		
		hashMap.put("25", "冲账");
		hashMap.put("30", "提现申请");
		//hashMap.put("31", "加入涨薪宝");
		hashMap.put("34", "APP充值");
		hashMap.put("35", "邀请返现");
		hashMap.put("37", "签约中资金退出");
//		if("107".equals(productType)){
			hashMap.put("98", "优享计划购买");
			hashMap.put("99", "优享计划转出");
//		}else{
			hashMap.put("48", "活期购买");
			hashMap.put("49", "活期转出");
//		}
		hashMap.put("51", "活动送理财金");
		hashMap.put("55", "定期加息收益");
		hashMap.put("56", "活动购买理财");
		hashMap.put("59", "定期专享收益");
		hashMap.put("74", "代金券使用");
		hashMap.put("89", "补偿");
		hashMap.put("101", "活动送礼包");
		return (String) hashMap.get(fundType);
	}
	
	/**
	 * 日期格式转换
	 * 
	 * yyyy-MM-dd → yyyy/MM/dd
	 * @throws ParseException 
	 * 
	 * */
	private String changeDateFormat(String date) throws ParseException {
		SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyy/MM/dd");
		
		if(date == null || "".equals(date)){
			return "";
		}
		
		return outFormat.format(inFormat.parse(date));
	}

	/**
	 * 根据合同类型，借款人id和债权子户ID 或 理财人id和债权子户id 查询合同镜像
	 * @param temp
	 * @return
	 * @throws Exception 
	 */
	@Override
	public AgreementMirror getAgreementMirrorByCons(AgreementMirror temp) throws Exception{
		return this.walletDao.getAgreementMirrorByCons(temp);
	}

	@Override
	public ResultDTO getFundFlowDetail(String jsonStr,String loginfo) throws Exception {
		// TODO Auto-generated method stub
		/**
		 * 调用核心接口 Q310002
		 * */
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		logger.info(loginfo+"核心返回"+rtnStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			JSONObject jsonMap = jsonObject.getJSONObject("flowInfoMap");
			if(jsonMap.size()>0){
				Map detailMap = flowDetail2Array(jsonMap);
				rtnMap.put("tradeAmount",jsonMap.get("tradeAmount"));
				rtnMap.put("status",jsonMap.get("status"));
				rtnMap.put("detailMap",detailMap);
			}
			ResultDTO result = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),
					ResultCode.SUCCESS.getType(),rtnMap);
			return result;
		}else{
			logger.debug("=====核心接口调用异常====="+loginfo);
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return new ResultDTO(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMsg(),
					ResultCode.FAILED.getType(),rtnMap);
		}
	}
	private Map flowDetail2Array(JSONObject JSONObj) throws ParseException {
		HashMap map= new HashMap<String,String[]>();
		String tradeType=JSONObj.getString("tradeType");//交易类型(01-活期购买，02-活期转出，03-充值，04-提现)
		String[] itemStr1; //前端显示中文列数组
		String[] itemStr2;//前端显示值数组
		switch (tradeType){
			case "01" :
				itemStr1=new String[]{"交易类型","交易时间","交易状态"};
				itemStr2=new String[3];
				itemStr2[0]=JSONObj.getString("tradeDesc");
				itemStr2[1]=JSONObj.getString("tradeTime");
				itemStr2[2]=JSONObj.getString("statusDesc");
				map.put("item1",itemStr1);
				map.put("item2",itemStr2);
				break;
			case "02" :
				itemStr1=new String[]{"交易类型","申请时间","交易时间","手续费","交易状态"};
				itemStr2=new String[5];
				itemStr2[0]=JSONObj.getString("tradeDesc");
				itemStr2[1]=JSONObj.getString("applyTime");
				itemStr2[2]=JSONObj.getString("tradeTime");
				itemStr2[3]=JSONObj.getString("feeAmount");
				itemStr2[4]=JSONObj.getString("statusDesc");
				map.put("item1",itemStr1);
				map.put("item2",itemStr2);
				break;
			case "03" :
				itemStr1=new String[]{"交易类型","交易时间","银行卡","交易状态"};
				itemStr2=new String[4];
				itemStr2[0]=JSONObj.getString("tradeDesc");
				itemStr2[1]=JSONObj.getString("tradeTime");
				String bankName1=JSONObj.getString("bankName");
				String bankCardNo1=JSONObj.getString("bankCardNo");
				itemStr2[2]=bankName1+"(尾号"+bankCardNo1.substring(bankCardNo1.length()-4)+")";
				itemStr2[3]=JSONObj.getString("statusDesc");
				map.put("item1",itemStr1);
				map.put("item2",itemStr2);
				break;
			case "04" :
				itemStr1=new String[]{"交易类型","申请时间","交易时间","银行卡","交易状态"};
				itemStr2=new String[5];
				itemStr2[0]=JSONObj.getString("tradeDesc");
				itemStr2[1]=JSONObj.getString("applyTime");
				itemStr2[2]=JSONObj.getString("tradeTime");
				String bankName2=JSONObj.getString("bankName");
				String bankCardNo2=JSONObj.getString("bankCardNo");
				itemStr2[3]=bankName2+"(尾号"+bankCardNo2.substring(bankCardNo2.length()-4)+")";
				itemStr2[4]=JSONObj.getString("statusDesc");
				map.put("item1",itemStr1);
				map.put("item2",itemStr2);
				break;
		}
		return map;
	}
}
